<template>

  <el-dialog
    :title="title"
    :visible.sync="show"
    width="40%"
    @close="close"
  >
    <el-form ref="form" :model="userDTO" :rules="rules" class="form" label-position="right" label-width="80px">
      <el-row>
        <el-col span="12">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="userDTO.userName" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
        <el-col v-if="!id" span="12">
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="userDTO.password" type="password" placeholder="请输入用户密码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="12">
          <el-form-item label="所属部门" prop="deptNames">
            <el-select
              v-model="userDTO.deptNames"
              clearable
              placeholder="请选择"
              multiple
              collapse-tags
              @remove-tag="removeTag"
              @clear="clear"
            >
              <el-input
                v-model="filterText"
                class="selectInput"
                :placeholder="placeholder"
              />
              <el-option :value="optionValue" style="height: auto" class="select-tree">
                <el-tree
                  ref="tree"
                  :data="tree"
                  :check-strictly="true"
                  :filter-node-method="filterNode"
                  show-checkbox
                  node-key="id"
                  highlight-current
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                />
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="userDTO.nickName" placeholder="请输入用户密码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="12">
          <el-form-item label="手机" prop="phone">
            <el-input v-model="userDTO.phone" placeholder="请输入手机" />
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userDTO.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="userDTO.sex" clearable placeholder="请选择性别">
              <el-option
                v-for="item in items"
                :key="item.itemCode"
                :label="item.itemName"
                :value="item.itemCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="状态" prop="state">
            <el-radio v-model="userDTO.state" :label="false">停用</el-radio>
            <el-radio v-model="userDTO.state" :label="true">正常</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="12">
          <el-form-item label="岗位" prop="postIds">
            <el-select
              v-model="userDTO.postIds"
              multiple
              collapse-tags
              clearable
              placeholder="请选择岗位"
            >
              <el-option
                v-for="item in posts"
                :key="item.id"
                :label="item.postName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select
              v-model="userDTO.roleIds"
              multiple
              collapse-tags
              clearable
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="个人介绍" prop="introduction">
          <el-input v-model="userDTO.introduction" type="textarea" :rows="2" placeholder="请输入个人介绍" />
        </el-form-item>
      </el-row>
      <el-row class="form-button">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button>取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { findDictItemByCode } from '@/api/sys/dict-item'
import { save, update, find } from '@/api/sys/user'
import { list } from '@/api/sys/post'
import { list as findRoles } from '@/api/sys/role'

export default {
  name: 'UserForm',
  components: {},
  props: {
    id: {
      type: Number,
      default: null
    },
    title: {
      type: String,
      default: '添加用户'
    },
    show: {
      type: Boolean,
      default: false
    },
    tree: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      isClearable: true,
      isAccordion: true,
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      userDTO: {
        userName: '', deptIds: [], deptNames: [], nickName: '', password: '123456', phone: '',
        email: '', sex: '', state: true, postIds: [], roleIds: []
      },
      options: [{ label: '停用', value: 0 }, { label: '正常', value: 1 }],
      radio: 1,
      rules: {
        userName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        deptNames: [
          { required: true, message: '请输入所属部门', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ]
      },
      items: [],
      optionValue: [],
      optionLabel: [],
      filterText: '',
      posts: [],
      roles: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    id(val) {
      if (val) {
        this.find()
      }
    }
  },
  created() {
    this.findDictItemByCode()
    this.findPost()
    this.findRole()
  },
  methods: {
    close() {
      this.$refs['form'].resetFields()
      this.userDTO = {
        userName: '', deptIds: [], deptNames: [], nickName: '', password: '123456', phone: '',
        email: '', sex: '', state: true, postIds: [], roleIds: []
      }
      this.$emit('update:show', false)
      this.$emit('update:id', null)
      this.filterText = ''
      this.clear()
    },
    async findDictItemByCode() {
      const { data } = await findDictItemByCode('sys_user_sex')
      this.items = data
    },
    getValue(value) {
      this.valueId = value
    },

    handleCheckChange() {
      const labels = []
      this.optionValue = this.$refs.tree.getCheckedNodes()
      this.optionValue.forEach(val => {
        labels.push(val.label)
      })
      this.userDTO.deptNames = labels
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    removeTag(value) {
      this.optionValue.splice(this.optionValue.findIndex(item => item.label === value), 1)
      this.$refs.tree.setCheckedNodes(this.optionValue)
    },
    clear() {
      this.optionValue = []
      this.$refs.tree.setCheckedNodes(this.optionValue)
    },
    save() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          const userDTO = { ...this.userDTO }
          delete userDTO.deptNames
          const deptIds = []
          this.optionValue.forEach(val => {
            deptIds.push(val.id)
          })
          userDTO.deptIds = deptIds
          if (this.id) {
            delete userDTO.password
            await update(userDTO)
            this.responseRes()
          } else {
            await save(userDTO)
            this.responseRes()
          }
        }
      })
    },
    async findPost() {
      const { data } = await list()
      this.posts = data
    },
    async findRole() {
      const { data } = await findRoles()
      this.roles = data
    },
    responseRes() {
      this.close()
      this.$parent.findPage()
    },
    async find() {
      const { data } = await find(this.id)
      this.userDTO = data
      const deptOptions = []
      const deptNames = []
      data.depts.map(val => {
        const obj = { id: val.id, label: val.deptName }
        deptOptions.push(obj)
        deptNames.push(val.deptName)
      })
      delete this.userDTO.depts
      this.optionValue = deptOptions
      this.userDTO.deptNames = deptNames
      this.$refs.tree.setCheckedNodes(this.optionValue)
    }
  }
}
</script>

<style scoped>

.select-tree {
  padding: 0 0;
}

.selectInput {
  padding: 10px;
}
</style>
